﻿using Autofac;
using MediatR;
using MediatRSample.Services;
using System;
using System.Collections.Generic;

namespace MediatRSample
{
    class Program
    {
        private static IContainer container;
        static void Main(string[] args)
        {
            try
            {
                TestAsync().Wait();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.WriteLine("Hello World!");
            Console.ReadKey();
        }

        private static async System.Threading.Tasks.Task TestAsync()
        {
            DenpendencyInit();

            var mediator = container.Resolve<IMediator>();
            //var res = await mediator.Send(new Ping() { MsgId = 400 });
            //Console.WriteLine(res);
           await mediator.Publish(new Notification() { MsgId = 500 });
        }

        private static void DenpendencyInit()
        {
            var builder = new ContainerBuilder();
            builder.RegisterType<Mediator>()
                .As<IMediator>()
                .InstancePerLifetimeScope();

            // request handlers
            builder
                .Register<SingleInstanceFactory>(ctx => {
                    var c = ctx.Resolve<IComponentContext>();
                    return t => c.TryResolve(t, out var o) ? o : null;
                })
                .InstancePerLifetimeScope();

            // notification handlers
            builder
                .Register<MultiInstanceFactory>(ctx => {
                    var c = ctx.Resolve<IComponentContext>();
                    return t => (IEnumerable<object>)c.Resolve(typeof(IEnumerable<>).MakeGenericType(t));
                })
                .InstancePerLifetimeScope();
            builder.RegisterAssemblyTypes(typeof(Program).GetType().Assembly).AsImplementedInterfaces();
            container = builder.Build();
        }
    }
}
